# -*- coding: iso-8859-15 -*-

#    SuperClipboard is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import gui
import config
import gtk
import gobject
gobject.threads_init()
import os
import socket
from NetworkServer import NetworkServer
from NetworkClient import NetworkClient
from sys import exit
from sys import executable
import cPickle as Pickle

class Copier():
    
    def __init__(self):
        self.config = config.Config(self)
        self.config.iswindows()
        self.loadsettings()
        self.loadstaticstettings()
        self.loadnetworksettings()
        
        self.clipboard = gtk.Clipboard()
        self.list_element = []
        self.run_seek()
        gobject.timeout_add(int(self.config.get('Timer')),self.run_seek)
        
        self.gui = gui.Gui(self)
        
        if self.config.network['ServerEnabled']:
            self.startNetworkServerThread()
        self.runningclient = []
        for client in self.config.network['Client']:
            if client['enable']:
                thcli = NetworkClient(self, client)
                self.runningclient.append(thcli)
                thcli.start()
        
        gtk.main()
####Network Functions
    def startNetworkServerThread(self):
        try:
            self.networkserver = NetworkServer(self)
            self.networkserver.start()
        except Exception as ex:
            print "thread : "+ex
            
    def stopNetworkServerThread(self):
        #connection vide afin que le boucle se termine
        try:
            self.networkserver.stop = False
            server =  ( "localhost", self.config.network["ServerPort"]) 
            tmpsocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
            tmpsocket.connect(server)
            tmpsocket.sendto ( "",server)
        except:
            pass
        
    def runningNetworkServerThread(self):
        try:
            return self.networkserver.is_alive()
        except:
            return False
          
######Settings function     
    def loadsettings(self):
        try:
            file = open(self.config.path['Conf'], 'r')
        except Exception:
            return False
        conf = {}
        tmpconf = Pickle.load(file)
        for key,element in self.config.conf.iteritems():
            try:
                conf[key]=tmpconf[key]
            except:
                conf[key]=element
        self.config.conf = conf
        return True

        
    def savesettings(self):
        path=self.config.path['Conf']
        path,filename = os.path.split(path)
        if not os.path.exists(path):
            os.makedirs(path)
        file_path = os.path.join(path,filename)
        file = open(file_path,'w')
        Pickle.dump(self.config.conf,file,True)
        file.close()
        
    def loadnetworksettings(self):
        try:
            file = open(self.config.path['Network'], 'r')
        except Exception:
            return False
        conf = {}
        tmpconf = Pickle.load(file)
        for key,element in self.config.network.iteritems():
            try:
                conf[key]=tmpconf[key]
            except:
                conf[key]=element
        self.config.network = conf
        return True

        
    def savenetworksettings(self):
        path=self.config.path['Network']
        path,filename = os.path.split(path)
        if not os.path.exists(path):
            os.makedirs(path)
        file_path = os.path.join(path,filename)
        file = open(file_path,'w')
        Pickle.dump(self.config.network,file,True)
        file.close()
    
    def loadstaticstettings(self):
        try:
            file = open(self.config.path['StaticConf'], 'r')
            self.config.staticcopy = Pickle.load(file)
            return True
        except Exception:
            return False
    
    def savestaticsettings(self):
        path=self.config.path['StaticConf']
        path,filename = os.path.split(path)
        if not os.path.exists(path):
            os.makedirs(path)
        file_path = os.path.join(path,filename)
        file = open(file_path,'w')
        Pickle.dump(self.config.staticcopy,file,True)
        file.close()
        
####Element functions
    def add_element(self,element):
        self.list_element.insert(0,element)
        self.rm_element(int(self.config.get('Number')))
        try:    
            self.networkserver.sendElement2All(element)
        except Exception:
            pass
    def rm_element(self,index):
        try:
            del self.list_element[index]
            return True
        except:
            return False
    
    def set_element_to_clipboard(self,widget,element):
        self.clipboard.set_text(element)
        
    def get_element(self):
        return self.list_element
    
    def run_seek(self):
        text = self.clipboard.wait_for_text()
        if text != None :
            add_clipboard = True
            for element in self.list_element:
                if element == text:
                    add_clipboard = False
            if add_clipboard:
                self.add_element(text)
        gobject.timeout_add(int(self.config.get('Timer')),self.run_seek)        
        return False
    
    def exit(self,widget=None):
        self.stopNetworkServerThread()
        exit(2)
        
if __name__ == "__main__":
    if os.name == 'nt':
        os.chdir(os.path.abspath(os.path.dirname(executable)))
    else:
        os.chdir(os.path.abspath(os.path.dirname(__file__)))
    Copier()